<script setup lang="ts">
import { ref,onMounted,onUpdated } from 'vue'
import * as Y from 'yjs'

let isShow = ref(false);

let showView=()=>{
    
    // Yjs documents are collections of
    // shared objects that sync automatically.
    const ydoc = new Y.Doc()
    // Define a shared Y.Map instance
    const ymap = ydoc.getMap()
    ymap.set('keyA', 'valueA')

    // Create another Yjs document (simulating a remote user)
    // and create some conflicting changes
    const ydocRemote = new Y.Doc()
    const ymapRemote = ydocRemote.getMap()
    ymapRemote.set('keyB', 'valueB')

    console.log(ymap.toJSON())
    console.log(ymapRemote.toJSON())

    // Merge changes from remote
    const update = Y.encodeStateAsUpdate(ydocRemote)
    Y.applyUpdate(ydoc, update)

    const update2 = Y.encodeStateAsUpdate(ydoc)
    Y.applyUpdate(ydocRemote, update2)

    // Observe that the changes have merged
    console.log(ymap.toJSON()) // => { keyA: 'valueA', keyB: 'valueB' }
    console.log(ymapRemote.toJSON())
}

onMounted(()=>{
    if(isShow.value==true){
        showView();
    }
})

onUpdated(()=>{
    if(isShow.value==true){
        showView();
    }
})

</script>

<template>
    <div class="hide"><input type="button" :value="`${isShow ? 'hide' : 'show'} yjs 4`" @click="isShow = !isShow"></div>
    <div v-if="isShow">
        <div>官方入门示例：<a src="https://docs.yjs.dev/" target="_blank">https://docs.yjs.dev/</a>，请 F12 查看控制台输出</div>
    </div>
</template>

<style scoped></style>